<template>
  <div class="userDetail">
    <el-card class="box-card">
      <div class="InfoList">
        <h4 class="textItem">
          主管信息
          <router-link :to="{path:'/user/index'}">
            <el-button class="backBtn" type="primary" size="mini">返回</el-button>
          </router-link>
        </h4>
        <div class="info-item">
          <div>
            <span class="tipText">用户名 : </span><span>{{userInfo.name}}</span>
          </div>
          <div>
            <span class="tipText">公司 : </span><span>{{userInfo.companyName}}</span>
          </div>
          <div>
            <span class="tipText">行业 : </span><span>{{userInfo.industryName}}</span>
          </div>
        </div>
        <div class="info-item">
          <div>
            <span class="tipText">电话 : </span><span>{{userInfo.phone}}</span>
          </div>
          <div>
            <span class="tipText">邮箱 : </span><span>{{userInfo.email}}</span>
          </div>
           <div class="customer">
            <el-button class="add-btn" @click="addCustomer" type="primary">新建</el-button>
           </div>
        </div>
      </div>
    </el-card>
    <el-table empty-text="暂无任何用户信息" :row-class-name="rowClassName" :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="客服姓名" >
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="所属公司">
        <template slot-scope="scope">
          <span>{{scope.row.companyName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户手机号">
        <template slot-scope="scope">
          <span>{{scope.row.phone}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="账号角色">
        <template slot-scope="scope">
          <span>{{ scope.row.roleId | roleMap(scope.row.roleId) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="优拨">
        <template slot-scope="scope" >
          <el-switch
            v-model="scope.row.call"
            @change="switchChange(scope.row)"
            :active-value="1"
            :inactive-value="2"
            active-color="#409eff"
            inactive-color="#ccc"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button @click="openEvent(scope.row,scope.$index)" type="warning"  size="small" icon="el-icon-circle-close-outline">{{ scope.row.enable === 1 ? '锁定' : '解锁' }}</el-button>
          <el-button v-if="scope.row.enable === 1" @click="openEditUser(scope.row)"  type="success"  size="small" icon="el-icon-edit">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" prev-text="上一页" next-text="下一页" @current-change="handleCurrentChange" :current-page.sync="listQuery.current"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog
      :visible.sync="confirmDialogVisible"
      width="30%"
      @open="setCurrentDialogText"
      @click="confirmDialogVisible = false"
    >
      <el-alert
        :title="currentText"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="enableEvent">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog @close="cancledialog('userForm')"  width="400px" :title="isAdd ? '新建' : '编辑'" :visible.sync="infoFormVisible">
      <el-form :model="updateInfo" :rules="userEditRules" ref="userForm">
        <el-form-item label="用户名" prop="name" :label-width="formLabelWidth">
          <el-input v-model.sync.trim="updateInfo.name"  auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="!isAdd" label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input  v-model.trim="updateInfo.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="isAdd" label="账号角色" prop="roleId" :label-width="formLabelWidth">
          <el-radio-group v-model="updateInfo.roleId">
              <el-radio :label.number="4">内部客服</el-radio>
              <el-radio :label.number="7">高级客服</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="电话" prop="phone" :label-width="formLabelWidth">
          <el-input  v-model.trim="updateInfo.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password" :label-width="formLabelWidth">
          <el-input  v-model.trim="updateInfo.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPwd" :label-width="formLabelWidth">
          <el-input  v-model.trim="updateInfo.checkPwd" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="infoFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="subHandler()">{{ isAdd ? '确认添加' :'确认修改' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAdvertiserList,
  editUser,
  addCustomer,
  enableUser,
  enableCall
} from "@/api/user";
import { getRanNum, base64encode } from "@/utils/index";

let updateObj = () => {
  return {
    name: "",
    email: "",
    phone: "",
    password: "",
    checkPwd: ""
  };
};
export default {
  name: "userDetail",
  data() {
    const checkpwdnum = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (!/^[a-zA-Z0-9\w_~!@#$%^&]{6,16}$/.test(value)) {
        callback(new Error("请输入数字，字母，字符，且字数为6～16位"));
      } else {
        callback();
      }
      return;
    };
    const checkPwd = (rule, value, callback) => {
      if (value !== this.updateInfo.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    const CheckTel = (rule, value, callback) => {
      let tempValue = value * 1;
      if (!value) {
        callback(new Error("请输入电话号码"));
      } else if (!Number.isInteger(tempValue)) {
        callback(new Error("电话号码必须是数字"));
      } else if (value.toString().length != 11) {
        callback(new Error("电话号码必须是11位"));
      } else {
        callback();
      }
    };

    const userEditRules = {
      name: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        {
          validator: function(rule, value, callback) {
            var regex = /^[\u4E00-\u9FA5A-Za-z0-9]+$/;
            if (!regex.test(value)) {
              callback(new Error("请不要输入特殊字符！"));
            } else {
              callback();
            }
          },
          trigger: "blur"
        }
      ],
      email: [{ message: "请输入邮箱", trigger: "blur" }],
      phone: [{ required: true, validator: CheckTel, trigger: "blur" }],
      password: [{ validator: checkpwdnum, trigger: "blur" }],
      roleId: [
        { required: true, message: "请选择账号角色", trigger: "change" }
      ],
      checkPwd: [{ validator: checkPwd, trigger: "blur" }]
    };

    return {
      isAdd: false,
      currentItem: null,
      currentIndex: null,
      confirmDialogVisible: false,
      currentText: "",
      formLabelWidth: "120px",
      list: [],
      total: null,
      listLoading: true,
      infoFormVisible: false,
      userEditRules: userEditRules,
      userInfo: null,
      listQuery: {
        current: 1,
        pagesize: 10,
        parentId: ""
      },
      updateInfo: updateObj()
    };
  },
  created() {
    this.fetchData();
  },
  watch: {
    // 如果路由有变化，会再次执行该方法
    $route(to, from) {
      if (to.path === "/user/details") {
        this.fetchData();
      }
    }
  },
  methods: {
    switchChange(item) {
      //改变后的值
      enableCall({ userId: item.userId, call: item.call * 1 })
        .then(res => {
          this.$message.success("设置成功");
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    setCurrentDialogText() {
      let text = this.currentItem.enable === 1 ? "锁定" : "解锁";
      this.currentText = "您确认要" + text + "该账号 ?";
    },
    openEvent(val, index) {
      this.confirmDialogVisible = true;
      this.currentItem = val;
      this.currentIndex = index;
    },
    fetchData() {
      this.list = [];
      let thisUserInfo = JSON.parse(localStorage.getItem("AD_USER"));
      this.userInfo = thisUserInfo;
      this.listQuery.parentId = thisUserInfo.userId;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      getAdvertiserList(this.listQuery)
        .then(response => {
          const temp = response.data;
          this.total = temp.total;
          this.list = temp.userInfo;
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
          this.$message.error(res);
        });
    },
    handleSizeChange(val) {
      this.listQuery.pagesize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getList();
    },
    openEditUser(item) {
      this.updateInfo = Object.assign({}, this.updateInfo, item);
      this.infoFormVisible = true;
    },
    cancledialog(userForm) {
      this.isAdd = false; //重置为false
      this.updateInfo = updateObj(); //重置为空
      //重置表单
      this.$refs[userForm].resetFields();
    },
    enableEvent(val, index) {
      let thisEnable = this.currentItem.enable === 1 ? 2 : 1;
      let thisUserId = this.currentItem.userId;
      let tempText = thisEnable === 2 ? "锁定" : "解锁";
      enableUser(
        {
          userId: thisUserId,
          enable: thisEnable,
          parentId: this.userInfo.userId
        },
        false
      )
        .then(res => {
          this.list[this.currentIndex].enable = thisEnable;
          this.$message.success(tempText + "成功");
          this.confirmDialogVisible = false;
        })
        .catch(res => {
          this.$message.success(tempText + "失败 " + res);
        });
    },
    rowClassName({ row, rowIndex }) {
      if (row.enable === 2) {
        return "warning-row";
      }
      return "";
    },
    subHandler() {
      this.$refs["userForm"].validate(valid => {
        if (!valid) {
          this.$message.error("修改失败,请确认您的信息后再提交");
          return;
        }
        let parentObj = {};
        parentObj["parentId"] = this.userInfo.userId;
        parentObj["industryId"] = this.userInfo.industryId;
        parentObj["companyId"] = this.userInfo.companyId;
        var tempData = Object.assign(
          {},
          this.updateInfo,
          this.isAdd ? parentObj : {}
        );
        delete tempData.checkPwd;
        if (!!tempData.password) {
          tempData.password =
            getRanNum(8) + base64encode(tempData.password) + getRanNum(8);
        }
        let tempfunc = this.isAdd ? addCustomer : editUser;
        tempfunc(tempData, false)
          .then(res => {
            this.$message.success(this.isAdd ? "新建成功" : "修改成功");
            this.getList();
            this.infoFormVisible = false;
          })
          .catch(res => {
            this.$message.error(res);
          });
      });
    },
    addCustomer() {
      this.infoFormVisible = true;
      this.isAdd = true;
    }
  }
};
</script>

<style type="text/scss" lang="scss" scoped>
@import "src/styles/mixin.scss";
.userDetail {
  .customer {
    float: right;
    > .add-btn {
      float: right;
      margin-right: 80px;
      margin-top: -10px;
    }
  }
  .el-alert--warning {
    background-color: #fff;
  }
  .backBtn {
    @include f-right;
  }
  .info-item {
    margin: 25px 0px 15px 50px;
    > div {
      display: inline-block;
      min-width: 250px;
    }
  }
  .box-card {
    margin-bottom: 15px;
  }
  .textItem {
    margin: 10px 0px;
    width: 100%;
  }
  .tipText {
    display: inline-block;
    margin-right: 10px;
    min-width: 80px;
    text-align: right;
  }
}
</style>
